public class Sort {
    //归并排序（递归法）
    public static void mergeSort(int[] array){

        decompose_merge(array,0,array.length-1);

    }
    private static void decompose_merge(int[] array,int left,int right){
        //分解
        if (left >= right){
            return;
        }
        int mid = (left + right) / 2;
        decompose_merge(array,left,mid);
        decompose_merge(array,mid+1,right);
        //合并
        merge(array,left,right,mid);
    }
    //合并两个有序数组
    private static void merge(int[] array,int left,int right,int mid){

        int s1 = left;
        int e1 = mid;

        int s2 = mid+1;
        int e2 = right;

        int k = 0;
        int[] count = new int[right - left + 1];

        while(s1 <= mid && s2 <= right) {
            if (array[s1] < array[s2]) {
                count[k++] = array[s1++];
            } else {
                count[k++] = array[s2++];
            }
        }
        while (s1 <= mid) {
            count[k++] = array[s1++];
        }
        while (s2 <= right) {
            count[k++] = array[s2++];
        }
        for (int i = 0; i < k; i++) {
            array[i + left] = count[i];
        }
    }
    //归并排序（非递归法）
    public static void mergeSort1(int[] array){
        int gap = 1;
        while (gap < array.length){
            for (int i = 0; i < array.length; i = i + 2 * gap) {
                int left = i;
                int mid = left + gap - 1;

                if (mid >= array.length){
                    mid = array.length - 1;
                }
                int right = mid + gap;
                if (right >= array.length){
                    right = array.length-1;
                }
                merge(array, left, right,mid);
            }
            gap = gap * 2;
        }
    }
    //计数排序()
    public static void countSort(int[] array){
        int max = array[0];
        int min = array[0];
       //求最大最小值
        for (int i = 0; i < array.length; i++) {
            if(max < array[i]){
                max = array[i];
            }
            if (min > array[i]){
                min = array[i];
            }
        }
        //计数
        int count[] = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            int a = array[i];
            count[a - min]++;
        }
        //返回数组
        int j = 0;
        for (int i = 0; i < array.length; i++) {
            while(count[i] != 0){
                array[j++] =i+min;
                count[i]--;
            }
        }
    }
}
